/**
 * 基于链表实现的队列
 *
 * @author Kevin
 * @date 2018-11-24
 */
public class LinkedListQueue<E> implements Queue<E> {

    private Node head, tail;

    private int size;

    public LinkedListQueue() {
        this.head = null;
        this.tail = null;
        this.size = 0;
    }

    @Override
    public int getSize() {
        return this.size;
    }

    @Override
    public boolean isEmpty() {
        return this.size == 0;
    }

    @Override
    public void enqueue(E e) {
        if (this.tail == null) {
            this.tail = new Node(e);
            this.head = tail;
        } else {
            this.tail.next = new Node(e);
            this.tail = this.tail.next;
        }

        this.size++;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Cannot dequeue from an empty queue.");
        }

        Node retNode = this.head;
        this.head = this.head.next;
        retNode.next = null;

        if (this.head == null) {
            this.tail = null;
        }

        this.size--;

        return retNode.e;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Queue is empty.");
        }

        return this.head.e;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Queue: front ");

        Node cur = this.head;
        while (cur != null) {
            sb.append(cur + "->");
            cur = cur.next;
        }

        sb.append("NULL tail");
        return sb.toString();
    }

    /**
     * 节点
     */
    private class Node {

        public E e;

        private Node next;

        public Node() {
            this(null, null);
        }

        public Node(E e) {
            this(e, null);
        }

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        @Override
        public String toString() {
            return e.toString();
        }

    }

    public static void main(String[] args) {

        LinkedListQueue<Integer> queue = new LinkedListQueue<>();
        for (int i = 0; i < 10; i++) {
            queue.enqueue(i);
            System.out.println(queue);

            if (i % 3 == 2) {
                queue.dequeue();
                System.out.println(queue);
            }
        }

    }

}
